class Site < ActiveRecord::Base
    has_and_belongs_to_many :users, :join_table => "roles_sites_users"
    has_and_belongs_to_many :roles, :join_table => "roles_sites_users"
    has_many :pages
    has_many :resources
    belongs_to :style
    
    def has_user?(username)
        user = User.find_first(["username = ?", username])
        if user
            for site in user.sites
                if site.title == self.title
                    return true
                end     
            end
        end
        return false
    end
    
    def has_logo?
        for res in self.resources
            if res.title == "logo.gif"
                return true
            end     
        end    
        return false
    end
    
    def can_be_edited_by_user?(username)
        self.has_user?(username)
    end
            
    def to_param
        return self.directory    
    end
    
    def get_page(page_title)
        if self.pages.length > 0
            
            for page in self.pages
                if page.title == page_title
                    return page
                end
            end
            return self.pages[0] 
        end
    end
    
    def self.find_by_directory(site_directory)
       if !site_directory
           @site = Site.find_first(["directory = ?", HOME_SITE])
       else
           @site = Site.find_first(["directory = ?", site_directory])
       end 
       
       if !@site
           @site = Site.new
       end
       return @site
    end
    
    def home_site?
        self.directory == HOME_SITE
    end
    
    def self.home_site
        site = Site.find_first(["directory = ?", HOME_SITE])
        if !site
            site = Site.new
        end
        return site
    end
    
    def delete_resource title
        # delete all (there should only be one)
        existing_resources = Resource.find_all(["site_id = ? AND title = ?", self.id, title])
        for res in existing_resources
            self.resources.delete res
        end
    end
    
    validates_presence_of :title, :directory
    validates_uniqueness_of :directory
 
end